import Vue from "vue";
import iview from "iview";
import Util from "../libs/util";
import VueRouter from "vue-router";
import Cookies from "js-cookie";
import { routers } from "./router";
import { pageReturn } from "../libs/tool";
import store from "../store";
import { getStore, getSession } from "../libs/storage";
import { isAppPages } from "../libs/regExCommon";
Vue.use(VueRouter);
// 路由配置
const RouterConfig = {
  mode: "history",
  routes: routers,
};
export const router = new VueRouter(RouterConfig);
router.beforeEach((to, from, next) => {
  iview.LoadingBar.start();

  Util.title(to.meta.title);
  if ((to.name == "single-app") | (to.name == "news-page")) {
    next();
  } else {
    if (!isAppPages(to.name)) {
      console.log(Cookies.get("locking"));
      if (Cookies.get("locking") == "1" && to.name !== "locking") {
        // 判断当前是否是锁定状态
        next({
          replace: true,
          name: "locking",
        });
      } else if (Cookies.get("locking") == "0" && to.name == "locking") {
        next(false);
      } else {
        if (getSession("accessToken")) {
          Cookies.set("locking", "0");
        }
        if (
          !getSession("accessToken") &&
          to.name !== "login" &&
          to.name !== "regist" &&
          to.name !== "regist-result" &&
          to.name !== "relate"
        ) {
          // 判断是否已经登录且前往的页面不是登录页
          next({
            name: "login",
          });
        } else if (
          getSession("accessToken") &&
          Cookies.get("userInfo") &&
          to.name == "login"
        ) {
          // 判断是否已经登录且前往的是登录页
          Util.title();
          next({
            name: pageReturn(getStore("roles")), //用户类型搞搞
          });
        } else {
          Util.toDefaultPage([...routers], to.name, router, next);
        }
      }
    } else {
      Util.toDefaultPage([...routers], to.name, router, next);
    }
  }
});

router.afterEach((to) => {
  // Util.openNewPage(router.app, to.name, to.params, to.query);

  iview.LoadingBar.finish();
  window.scrollTo(0, 0);
});
